#include "videoio_server.h"

/*---------------------------------------------------------
	传视频服务器端
	cpuid:		绑定到某核
	sock_tcp:   服务器端套接字 tcp
----------------------------------------------------------*/
void videoTransServer(int cpuid, int sock_tcp){
	cpu_set_t mask;

	CPU_ZERO(&mask);
	CPU_SET(cpuid, &mask);

	if (pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask) < 0)
		cerr << "set thread affinity failed" << endl;

	printf("Bind videoTransServer process to CPU %d\n", cpuid); 

	cv::VideoWriter vid_writer;
	video_property video_probs;
	read(sock_tcp, &video_probs, sizeof(video_property));
	while(1)
    {
       if(video_probs.Video_width!=0)
       {
            //cout << Video_width << " " << Video_height << endl;
            vid_writer  = cv::VideoWriter(SAVE_PATH, video_probs.Video_fourcc, video_probs.Fps,
										  cv::Size(video_probs.Video_width, video_probs.Video_height));
            break;
       }
    }

	int i =0;
	while(1){
		if (queueInput_server.size() > 300){
			sleep(1);
			continue;
		}
		char buf[65536];
		std::vector<uchar> decode;
		int n = 0, idx = 0, cur = 0, tmp = 0, length = sizeof(int);// length是INT预计长度
		// 1 读idx
		while(cur < length){
			if((tmp = read(sock_tcp, &idx+cur, length-cur)) < 0){
				printf("videoio_sever.cpp:read idx error.\n");
				bReading = false;
				return;
			}
			else if(tmp == 0){
				bReading = false;
				return;
			}
			cur += tmp;
		}
		// 2 读图片压缩后的长度n
		cur = 0;
		while(cur < length){
			if((tmp = read(sock_tcp, &n+cur, length-cur)) <= 0){
				printf("videoio_client.cpp:read 图片压缩后的长度n error.\n");
				bReading = false;
				return;
			}
			cur += tmp;
		}
		// 3 读图片
		cur = 0;
		while(cur < n){
			if((tmp = read(sock_tcp, buf+cur, n-cur)) <= 0){
				printf("videoio_client.cpp:read 图片 error.\n");
				bReading = false;
				return;
			}
			cur += tmp;
		}
		
		int pos = 0;
		while (pos < n)
		{
			decode.push_back(buf[pos++]);//存入vector
		}
		buf[n] = 0;
		Mat img = imdecode(decode, CV_LOAD_IMAGE_COLOR);//图像解码

		mtxQueueInput_server.lock();
		queueInput_server.push(make_pair(idx, img));
		mtxQueueInput_server.unlock();
		printf("服务器缓冲队列大小: %d 当前idx: %d\n", queueInput_server.size(), idx);
	}
	
}